package services

import (
	"errors"

	"gorm.io/gorm"

	"chat-app/internal/app/models"
)

type UserService interface {
	// 获取用户信息
	GetUser(userID uint) (*models.User, error)
	// 搜索用户（按手机号或昵称）
	SearchUsers(query string) ([]*models.User, error)
	// 更新用户昵称
	UpdateUserNickname(userID uint, nickname string) error
	// 获取用户的好友状态
	GetFriendStatus(userID, targetID uint) (string, error)
}

type userService struct {
	db *gorm.DB
}

func NewUserService(db *gorm.DB) UserService {
	return &userService{db: db}
}

func (s *userService) GetUser(userID uint) (*models.User, error) {
	var user models.User
	if err := s.db.Where("id = ?", userID).First(&user).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, errors.New("user not found")
		}
		return nil, err
	}

	// 敏感信息处理，不要返回密码
	user.Password = ""
	return &user, nil
}

func (s *userService) SearchUsers(query string) ([]*models.User, error) {
	var users []*models.User
	if query == "" {
		return nil, errors.New("search query is required")
	}

	searchPattern := "%" + query + "%"
	err := s.db.Where("phone LIKE ? OR nickname LIKE ?", searchPattern, searchPattern).
		Limit(10). // 限制搜索结果数量
		Find(&users).Error

	if err != nil {
		return nil, err
	}

	// 移除敏感信息
	for i := range users {
		users[i].Password = ""
	}

	return users, nil
}

func (s *userService) UpdateUserNickname(userID uint, nickname string) error {
	if nickname == "" {
		return errors.New("nickname cannot be empty")
	}

	tx := s.db.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
		}
	}()

	if err := tx.Model(&models.User{}).
		Where("id = ?", userID).
		Update("nickname", nickname).Error; err != nil {
		tx.Rollback()
		return err
	}

	return tx.Commit().Error
}

func (s *userService) GetFriendStatus(userID, targetID uint) (string, error) {
	if userID == targetID {
		return "", errors.New("cannot check friend status with yourself")
	}

	// 检查是否是好友
	var friend models.Friend
	if err := s.db.Where("user_id = ? AND friend_id = ?", userID, targetID).First(&friend).Error; err == nil {
		return "friends", nil
	}

	// 检查是否有待处理的好友请求
	var request models.FriendRequest
	if err := s.db.Where("requester_id = ? AND requestee_id = ?", userID, targetID).
		Or("requester_id = ? AND requestee_id = ?", targetID, userID).
		First(&request).Error; err == nil {
		if request.RequesteeID == userID && request.Status == models.RequestStatusPending {
			return "received_request", nil
		}
		if request.RequesterID == userID && request.Status == models.RequestStatusPending {
			return "sent_request", nil
		}
	}

	return "no_relation", nil
}
